<?php
/**
 * XmuSlh, web platform of Student Association Federation of Xiamen University
 * 
 * Rewritting one or some pages of StatusNet. 
 * To get the original version, please visit <http://status.net/>.
 * 
 * StatusNet, the distributed open-source microblogging tool
 * 
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * The Picture class for table 'picture'.
 * Associated with a micro news.
 * 
 * @author		ytukie <ytukie@gmail.com>
 * @version		0.1
 */

// XmuSlh only.
if ( !defined('XMUSLH')) { exit(1); }

require_once INSTALLDIR . '/classes/Memcached_DataObject.php';

// Definitions.
// Column of status reserves.

// Definitions.
define('PICTURE_THUMBNAIL_MAXWIDTH',		slh_config('picture', 'thumbnail_maxwidth'));
define('PICTURE_THUMBNAIL_MAXHEIGHT',		slh_config('picture', 'thumbnail_maxheight'));

class Picture extends Memcached_DataObject
{
	public $__table = 'picture';				// table name
	public $id;								// int(11)  primary_key not_null
	public $status;							// tinyint(4)
	public $news_id;						// int(11)  foreign_key not_null
	public $picturename;					// varchar(255)  not_null
	public $mimetype;						// varchar(32)
	public $width;							// int(11)
	public $height;							// int(11)
	public $created;						// datetime  not_null
	
	// Static get
	function staticGet($key, $value = null)
	{
		return Memcached_DataObject::staticGet('picture', $key, $value); 
	}
	
	/**
	 * Delete the picture both in database and filesystem.
	 */
	function delete()
	{
		@unlink($this->picturepath());
		@unlink($this->thumbnailpath());
		
		parent::delete();
	}
	
	/**
	 * Remove the picture item if in the air.
	 * 
	 * While a new picture is uploaded successfully, then check the old one!
	 * See the uploadedpicture_id is existed already, then clean it up!
	 * Or the micro news fail to post. Then clean it up.
	 */
	static function removeIfAiredPicture($picture_id)
	{
		if ( !empty($picture_id)) {
			if ( !Picture::checkIfSetNewsid($picture_id)) {
				// If not set, then consider it's a picture item in air, most probable being
				// replace by another newly uploading pirture! Delete it!
				$uploadedpicture = Picture::staticGet('id', $picture_id);
				$uploadedpicture->delete();
			}
		}
	}
	
	/**
	 * Set the news_id for the picture item which is belong to one successfully
	 * posted micronews.
	 */
	static function setNewsidById($news_id, $picture_id)
	{
		$query = 'UPDATE `picture` SET `news_id` = ' . $news_id .
				 ' WHERE `id` = ' . $picture_id;
		
		$picture = new Picture();
		$picture->query($query);
		
		$result = false;
		if ($picture->fetch()) {
			$result = true;
		}
		
		$picture->free();
		$picture = null;
	}
	
	/**
	 * Check the picture by given picture_id if it's new_id is set.
	 * If so, or no such picture, it's abusive.
	 * 
	 * 0 is the default null picture singnal.
	 * 
	 * @return true, set, false, not set.
	 */
	static function checkIfSetNewsid($picture_id)
	{
		if (0 == intval($picture_id)) {
			return false;	
		}
		
		$query = 'SELECT `news_id` FROM `picture` ' .
				 'WHERE `id` = ' . $picture_id;
		
		$picture = new Picture();
		$picture->query($query);
		
		$result = true;
		if ($picture->fetch()) {
			if ( empty($picture->new_id)) {
				$result = false;
			}
		}
		
		$picture->free();
		$picture = null;
		
		return $result;
	}
	
	/**
	 * Add the infomation of picture into database.
	 */
	static function add($fields)
	{
		// Magically put fields into current scope.
		extract($fields);
		
		$picture = new Picture();
		$picture->status = 0;
		$picture->news_id = $news_id;
		$picture->picturename = $picturename;
		$picture->mimetype = $mimetype;
		$picture->width = $width;
		$picture->height = $height;
		$picture->created = slh_sql_now();
		
		$picture_id = $picture->insert();
		if (empty($picture_id)) {
			slh_log_db_error($picture, 'INSERT', __FILE__);
			return false;
		}
		
		return $picture_id;
	}
	
	/**
	 * Get the thumbnail url by given news_id.
	 */
	static function getThumbnailUrlByNewsid($news_id)
	{
		
		$query = 'SELECT `picturename` FROM `picture` ' .
				 'WHERE `news_id` = ' . $newsid;
		
		$picture = new Picture();
		$picture->query($query);
		
		$result = false;
		if ($picture->fetch()) {
			$result = Picture::url(Picture::filename2Thumbnailname($picture->picturename));
		}
		
		$picture->free();
		$picture = null;
		
		return $result;
	}
	
	/**
	 * Get the picture path.
	 */
	function picturepath()
	{
		return Picture::path($this->picturename);
	}
	
	/**
	 * Get the picture url.
	 */
	function pictureurl()
	{
		return Picture::url($this->picturename);
	}
	
	/**
	 * Get the thumbnail path.
	 */
	function thumbnailpath()
	{
		return Picture::path(Picture::filename2Thumbnailname($this->picturename));
	}
	
	/**
	 * Get the thumbnail url.
	 */
	function thumbnailurl()
	{
		return Picture::url(Picture::filename2Thumbnailname($this->picturename));
	}
	
	/**
	 * Change to original filename(picturename) to thumbnail name.
	 * TODO: Fix the naming standard, more simplified?
	 */
	static function filename2Thumbnailname($filename)
	{
		return strtr($filename, array('o' => 't'));
	}
	
	/**
	 * The barename of the original file.
	 */
	static function filename($id, 
							 $extension, 
							 $extra = null)
	{
		return 'o-' . $id . (($extra) ? ('-' . $extra) : '') . $extension;
	}
	
	/**
	 * The absolute path including the barename. (../xx.jpg).
	 */
	static function path($filename)
	{
		$dir = slh_config('picture', 'dir');
		
		if ($dir[strlen($dir) - 1] != '/') {
			$dir .= '/';
		}
		
		return $dir . $filename;
	}
	
	/**
	 * The unique url.
	 */
	static function url($filename)
	{
		$path = slh_config('picture', 'path');
		
		if ($path[strlen($path) - 1] != '/') {
			$path .= '/';
		}
		
		if ($path[0] != '/') {
			$path = '/' . $path;
		}
		
		// FIXME: The extra server for avatar.
		$server = slh_config('picture', 'server');
		
		return 'http://' . $server . $path . $filename;
	}
	
	// Fake default image.
	static function defaultPicture()
	{
		return slh_config('picture', 'path') . 'default.jpg';
	}
}
?>